<template>
  <section v-loading="loading">
    <el-table :data="answerList" border style="text-align: center" >
      <el-table-column type="index" width="50"/>
      <el-table-column label="答卷" :formatter="formatDate" width="160" header-align="center">
        <template slot-scope="scope">
          {{scope.row.instance.title}}
        </template>
      </el-table-column>
      <el-table-column prop="begin" label="答题时间" :formatter="formatDate" width="260" header-align="center">
      </el-table-column>
      <el-table-column label="状态" width="260" header-align="center">
        <template slot-scope="scope">
          <el-row style="color: green" v-if="scope.row.data.sum">已生成√</el-row>
          <el-button type="text" @click="sum(scope.row)" v-if="!scope.row.data.sum">生成分数</el-button>
          <!--<el-button type="text" @click="sum(scope.row)" >生成分数</el-button>-->
        </template>
      </el-table-column>
      <el-table-column label="操作" header-align="center" width="80px">
        <template slot-scope="scope">
          <el-button type="text" @click="btnDetailAnswer(scope.row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination v-show="allAnswerPage>0" style="margin-top:10px;" small layout="prev, pager, next" :page-count="allAnswerPage" @current-change="nextAnswerPage"></el-pagination>
    <el-dialog :visible.sync="showAnswerDialog" >
      <el-row>
        <el-col :span="10">
          <tacticsTable :tactics="tactics" v-if="showAnswerDialog" :currAnswer="currAnswer"></tacticsTable>
        </el-col>
        <el-col :span="12" style="margin-left: 15px">
          <chartsCom :currAnswer="currAnswer" ></chartsCom>
        </el-col>
      </el-row>
      <el-container style="height: 400px; border: 1px solid #eee;margin-top: 10px">
        <el-main>
          <el-pagination v-show="totalPage>0" style="margin-top:10px;" small layout="prev, pager, next" :page-count="totalPage" @current-change="goPage"> </el-pagination>
          <el-row v-if="showAnswerDialog">
            <QaViewController v-for="section of selPage.sections" :key="section.key"
                              :question="section" :tactics="tactics"></QaViewController>
          </el-row>
        </el-main>
      </el-container>
    </el-dialog>
    <!--<el-dialog :visible.sync="look" >-->
      <!--<chartsCom :currAnswer="currAnswer" v-if="look"></chartsCom>-->
    <!--</el-dialog>-->
  </section>
</template>

<script>
  import {mapGetters, mapActions, mapMutations} from 'vuex'
  import DateFormat from '@/common/date-formater'
  import QaViewController from "@/components/health_check/view/index";
  import tacticsTable from "./tacticsTable";
  import chartsCom from "./charts";
  import errHandler from '@/assets/errHandler.js'
  export default {
    name: "answer",
    components:{QaViewController,tacticsTable,chartsCom},
    data() {
      return {
        showAnswerDialog:false,
        selPage:{},//答卷页面
        answerList:[],//所有答卷
        totalPage:0,//答卷内翻页
        allAnswerPage:0,//答卷列表页面翻页
        loading:false,
        currAnswer:null,//当前答卷
        tactics:null,//策略根目录，含子目录
        tacticsList:[],//策略所有最后一级目录
        look:false,
        female:[
          {id:1,max:66},
          {id:2,max:45},
          {id:3,max:45},
          {id:4,max:111},
          {id:5,max:93},
        ],
        male:[
          {id:1,max:63},
          {id:2,max:45},
          {id:3,max:45},
          {id:4,max:111},
          {id:5,max:84},
        ],
      }
    },
    watch:{
    },
    computed:{
    },
    created(){
      // this.loading = true
      this.getAnswerListByPage()//加载所有答卷
      this.getTactics()//加载策略，含子目录
    },
    methods: {
      ...mapActions({
        fetch: 'fetch'
      }),
      lookPoint(row){
        this.currAnswer= this.makePageSection(row)
        this.look=true
      },
      makePageSection(row){//把一个问卷里所有page的matedata处理一下
        row.answerPages.forEach(c=>{
          c.sections = JSON.parse(c.metadata)
          c.sections.forEach(s=>{
            if(s.options){
              s.options.forEach(o=>{
                if(o.tactics){
                  s.tactics=o.tactics
                  s.point=o.point
                }
              })
            }
          })
        })
        return row
      },
      getUserInfo(row,sumUi){
        this.fetch({name:"getUser",data:{uid:row.userId}})
          .then(res=>{
            console.log(res)
            if(res.sex === 1){
              this.male.forEach(m=>{
                sumUi.forEach(s=>{
                  if(s.id === m.id)
                    s.max = m.max
                  s.min = -20
                })
              })
            }else if(res.sex === 2){
              this.female.forEach(m=>{
                sumUi.forEach(s=>{
                  if(s.id === m.id)
                    s.max = m.max
                  s.min = -20
                })
              })
            }
            this.updateAnswer(sumUi,row)
          })
          .catch(err=>{
            console.log(err)
            errHandler.handle(this,err)
          })
      },
      sum(row){//计算答卷的策略分，并更新答卷
        console.log(row)
        this.loading=true
        // console.log(row)
        row = this.makePageSection(row)
        let tacticsArray=[]
        row.answerPages.forEach(ap=>{
          if(ap.sections){
            //找到答案和策略、计分
            let tmp = this.searchATS(ap.sections)
            tacticsArray=tacticsArray.concat(tmp)
          }
        })
        //做一个总的合集
        let sumUi = this.makeTacticsSum(tacticsArray)
        //计算根目录
        sumUi.forEach(s=>{
          if(s.childrens){
            let sumP = this.sumRoot(s.childrens)
            s.point=sumP
          }
        })
        this.max.forEach(m=>{
          sumUi.forEach(s=>{
            if(s.id === m.id){
              s.max=m.max
            }
          })
        })
        this.getUserInfo(row,sumUi)
      },
      sumRoot(sumUi){
        let num=0
        sumUi.forEach(s=>{
          if(s.point){
            if(!s.childrens){
              num += Number(s.point)
            }else {
              num = this.sumRoot(s.childrens)
            }
          }
        })
        return num
      },
      updateAnswer(sumUi,row){//更新答卷
        let p={answerId:row.id}
        p.data={sum:sumUi}
        this.fetch({name:"updateAnswer",data:{...p}})
          .then(res=>{
            console.log(res)
            this.loading=false
            row.data.sum=sumUi
          })
          .catch(err=>{
            console.log(err)
            errHandler.handle(this,err)
          })
      },
      makeTacticsSum(tacticsArray){//将相同的策略分加在一起
        let sumUi=[]
        tacticsArray.forEach(ta=>{
          let index = sumUi.findIndex(su=>su.id === ta.tactics[ta.tactics.length-1])
          if(index <0){
            sumUi.push({id:ta.tactics[ta.tactics.length-1],point: Number(ta.point)})
          }else {
            sumUi[index].point += Number(ta.point)
          }
        })
        //做一个纯净版的壳子
        let box=this.makeBox(this.tactics)
        //把sumUi的内容放到策略里
        let tacticsUi = this.makeTacticsUi(box,sumUi)
        return tacticsUi
      },
      makeBox(tactics){
        let array=[]
        tactics.forEach(t=>{
          let tmp={id:t.id,name:t.name}
          array.push(tmp)
          if(t.childrens){
            tmp.childrens=this.makeBox(t.childrens)
          }
        })
        return array
      },
      makeTacticsUi(array,sumUi){
        let newArray=[]
        array.forEach(t=>{
          sumUi.forEach(s=>{
            if(t.id === s.id){
              t.point = s.point
            }else if(t.childrens){
              this.makeTacticsUi(t.childrens,sumUi)
            }
          })
        })
        this.loading =false
        return array
      },
      searchATS(sections){//找到答案匹配的策略、分数
        let obj=[]
        let section = sections.find(s=>s.answer)
        sections.forEach(section=>{
          if(section.answer !== ''){
            // console.log(section)
            if(section.type==='radio'){
              let tmp = section.options.find(o=>section.answer === o.text)
              if(tmp && tmp.tactics){
                let tmp2={tactics:tmp.tactics,point:tmp.point}
                obj.push(tmp2)
              }
            }else if(section.type === 'checkbox'){
              section.options.forEach(o=>{
                if(section.tactics){
                  section.answer.forEach(a=>{
                    if(a === o.text){
                      let tmp2= {tactics:o.tactics,point:o.point}
                      obj.push(tmp2)
                    }
                  })
                }
              })
            }
          }
        })
        return obj
      },
      formatDate(row, column, cellValue, index){
        return DateFormat.formatDatetime(cellValue)
      },
      nextAnswerPage(val){//答卷列表翻页
        this.getAnswerListByPage(val-1)
      },
      goPage(val){//答卷页面翻页
        this.getSelPage(val-1)
      },
      getAnswerListByPage(pageNo){//加载所有答卷
        this.fetch({name:"getAnswerListByPage",data:{page:pageNo?pageNo:0}})
          .then(res=>{
            console.log(res.content)
            this.loading = false
            this.answerList=res.content//所有答卷列表
            this.allAnswerPage=res.totalPages//答卷列表翻页页数
          })
          .catch(err=>{
            console.log(err)
            errHandler.handle(this,err)
          })
      },
      btnDetailAnswer(row){//显示问卷详细
        this.currAnswer= this.makePageSection(row)
        this.getSelPage()
        this.showAnswerDialog = true
      },
      getTactics(){//加载策略列表，含子目录
        this.fetch({name:"getTacticsList"})
          .then(res=>{
            this.tactics=res
            this.tacticsList=[]
            this.makeTacticsList(res)//制作所有子级策略数据
          })
          .catch(err=>{
            console.log(err)
            errHandler.handle(this,err)
          })
      },
      makeTacticsList(t){//制作所有子级策略数据
        t.forEach(i=>{
          if(!i.childrens){
            this.tacticsList.push(i)
          }else {
            this.makeTacticsList(i.childrens)
            return
          }
        })
      },
      getSelPage(pageNo){//获取答卷内页面
        this.selPage = this.currAnswer.answerPages[pageNo?pageNo:0]
        this.totalPage = this.currAnswer.answerPages.length
      },
    }
  }
</script>

<style scoped>

</style>
